#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai

import sys
import re
from datetime import datetime, timedelta

def loop_once(cyg_file, nm_list):
    cyg_list = []
    cyg_count = 0
    for cyg_line in cyg_file:
        if cyg_count == len(nm_list):
            break
        cyg_rx = "^\[(.+)\] +(%s.*)" % nm_list[cyg_count][0]
        cyg_re = re.match(cyg_rx, cyg_line)
        if cyg_re != None:
            #### for minicom ####
            cyg_dt = datetime.strptime(cyg_re.group(1), "%Y-%m-%d %H:%M:%S.%f")
            #print cyg_line.rstrip('\n\r')
            #print cyg_dt
            cyg_entry = [cyg_re.group(2).rstrip('\n\r'), cyg_dt]
            cyg_list.append(cyg_entry)
            cyg_count += 1

    if cyg_count != len(nm_list):
        print "Parse Error!!! the log could not go through all check points %d/%d" % (cyg_count, len(nm_list))

    cyg_base = None
    cyg_last = None
    for item in cyg_list:
        if cyg_base == None:
            cyg_base = item[1]
        if cyg_last != None:
            cyg_delta = item[1] - cyg_last
            print "\tDelta %s" % (cyg_delta)
        cyg_last = item[1]
        print "[%s] %s" % (item[1] - cyg_base, item[0])

    return cyg_count
    

def main():
    if len(sys.argv) < 3:
        print "Usage: %s" % sys.argv[0]
        sys.exit(2)

    nm_list = []
    nm_file = open(sys.argv[1], 'r')
    for nm_line in nm_file:
        nm_re = re.match("^#.*", nm_line)
        if nm_re:
            continue
        nm_entry = [nm_line.rstrip('\n\r'), 0]
        nm_list.append(nm_entry)

    print "Number of Check Points %d" % len(nm_list)
    #print nm_list

    cyg_file = open(sys.argv[2], 'r')
    loops = 0

    count = loop_once(cyg_file, nm_list)
    while count != 0:
        print "Loop count %d matched %d\n" % (loops, count)
        count = loop_once(cyg_file, nm_list)
        loops += 1

    
if __name__ == "__main__":
    main()
